package org.finesys.common.excel.aop;

import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.finesys.common.excel.annotaion.ResponseExcel;
import org.finesys.common.excel.processor.NameProcessor;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.time.LocalDateTime;
import java.util.Objects;

@Aspect
@RequiredArgsConstructor
public class DynamicNameAspect {
    public static final String EXCEL_NAME_KEY = "__EXCEL_NAME_KEY__";
    private final NameProcessor nameProcessor;

    @Before("@annotation(excel)")
    public void around(JoinPoint joinPoint, ResponseExcel excel) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String name = excel.name();
        //
        if (!StringUtils.hasText(name)) {
            name = LocalDateTime.now().toString();
        } else {
            name = nameProcessor.doDetermineName(joinPoint.getArgs(), methodSignature.getMethod(), excel.name());
        }
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        Objects.requireNonNull(requestAttributes).setAttribute(EXCEL_NAME_KEY, name, RequestAttributes.SCOPE_REQUEST);
    }

}
